#include <brpc/channel.h>
#include <thread>
#include "main.pb.h"

void Callback(brpc::Controller* controller, ::example::EchoResponse* response)
{
    std::unique_ptr<brpc::Controller> controller_guard(controller);
    std::unique_ptr<example::EchoResponse> response_guard(response);
    if(controller->Failed())
    {
        std::cout << "RPC调用失败: " << controller->ErrorText() << std::endl;
        return;
    }
    std::cout << "收到响应: " << response->message() << std::endl;
}

int main(int argc, char* argv[])  
{
    // 1.构造一个Channel对象，用于和服务端通信
    brpc::ChannelOptions options;
    options.connect_timeout_ms = -1;    // 连接超时时间，-1表示不超时
    options.timeout_ms = -1;            // 调用超时时间，-1表示不超时
    options.max_retry = 3;              // 最大重试次数
    options.protocol = "baidu_std";     // 协议类型，baidu_std表示百度标准协议
    brpc::Channel channel;
    int ret = channel.Init("127.0.0.1:8080", &options);
    if(ret == -1)
    {
        std::cout << "初始化信道失败" << std::endl;
        return -1;
    }

    // 2.构造EchoService_Stub对象，用于RPC调用
    example::EchoService_Stub stub(&channel);
    // 3.进行RPC调用，并获取响应
    example::EchoRequest request;
    request.set_message("你好，我是客户端");

    brpc::Controller* controller = new brpc::Controller();
    example::EchoResponse* response = new example::EchoResponse();
    auto closure = google::protobuf::NewCallback(Callback, controller, response);
    
    // ---------同步调用---------
    // stub.Echo(controller, &request, response, nullptr);
    // if(controller->Failed())
    // {
    //     std::cout << "RPC调用失败: " << controller->ErrorText() << std::endl;
    //     return -1;
    // }
    // std::cout << "收到响应: " << response->message() << std::endl;
    // delete controller;
    // delete response; 

    // ---------异步调用---------
    stub.Echo(controller, &request, response, closure);  
    std::cout << "异步调用结束" << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(3));

    return 0;
}